package school.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import school.domain.User;
import school.mapper.UserMapper;
import school.support.BaseController;
import school.support.util.ParamUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

@Controller
@RequestMapping("user")
public class UserController extends BaseController {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户列表
     *
     * @param user
     * @param pageNum
     * @param model
     * @return
     */
    @RequestMapping("list")
    public String list(User user, @RequestParam(defaultValue = "1") Integer pageNum, Model model) {
        PageHelper.startPage(pageNum, 10);
        Example example = new Example(User.class);
        if (user.getUsername() == null) user.setUsername("");
        example.createCriteria()
                .andLike("username", "%" + user.getUsername() + "%")
                .andEqualTo("type", "default");
        PageInfo<User> pageInfo = new PageInfo<>(userMapper.selectByExample(example), 5);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("requestUrl", request.getRequestURI() + "?" + ParamUtils.params2String(request));
        return "user/list";
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @RequestMapping("del/{id}")
    public String del(@PathVariable Integer id) {
        userMapper.deleteByPrimaryKey(id);
        return refresh();
    }

    /**
     * 添加用户
     *
     * @return
     */
    @GetMapping("add")
    public String add() {
        return "user/add";
    }

    /**
     * 添加用户
     *
     * @return
     */
    @PostMapping("add")
    public String add(User user) {
        user.setAddtime(new Date());
        user.setType("default");
        userMapper.insertSelective(user);
        return "redirect:list.do";
    }

}
